<script>
import {ElMessage, ElNotification} from "element-plus";
import router from "../../router/index.js";
import CryptoJS from "crypto-js"
import request from "../../utils/Request.js";
import {Back} from "@element-plus/icons-vue";

export default {
  components: {Back},

  data() {
    return {
      user: {
        id: '',
        email: '',
        password: '',
        passwordConfirm: '',
        code: '',
      },
      rules: {
        email: [
          {required: true, message: '请输入邮箱地址', trigger: 'change'},
          {type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur'},
        ],
        password: [{
          validator: (rule, value, callback) => {
            if (value === '')
              callback(new Error('请输入密码'))
            else if (!new RegExp("^[a-zA-Z0-9]{6,18}$").test(value))
              callback(new Error('请输入6到18位的不包括特殊字符的密码'))
            else
              callback()
          }, trigger: 'blur'
        }],
        passwordConfirm: [{
          validator: (rule, value, callback) => {
            if (value === '')
              callback(new Error('请再一次输入密码'))
            else if (value !== this.user.password)
              callback(new Error('两次输入的密码不一致'))
            else
              callback()
          }, trigger: 'blur'
        }]
      },
      countDownValue: 0,
      isCountDown: false,
      disableButton: false,
      // 是不是密码重置
      isReset: false
    }
  },
  methods: {
    sendForgetUrl() {
      let form = this.$refs['formRef']
      // console.log(this.formData)

      form.validate((valid) => {
        if (valid) {
          if (!this.isCountDown) {
            this.disableButton = true
            // 发送验证码
            // 邮箱Base64编码
            let emailEncoded = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(this.user.email))
            // console.log(CryptoJS.enc.Utf8.stringify(CryptoJS.enc.Base64.parse(emailEncoded)))
            request({
              method: 'post',
              url: '/api/uaa/forget/code?email=' + emailEncoded,
            })
                .then(resp => {
                  let data = resp.data
                  if (data.code === 0) {
                    // 发送成功
                    ElMessage.success("发送邮件成功，请注意查收！")
                    this.isCountDown = true;
                    this.countDownValue = Date.now() + 60000
                  } else if (data.code === 1204) {
                    ElMessage.error('请勿频繁发送邮件！')
                    this.isCountDown = true;
                    this.countDownValue = Date.now() + 60000
                  } else {
                    ElMessage.error(data.msg)
                  }
                  this.disableButton = false
                })
                .catch(err => {
                  console.log(err)
                  if (!this.isCountDown)
                    ElMessage.error('发送邮件失败！')
                  this.disableButton = false
                })

          } else {
            ElMessage.error('请勿频繁发送邮件！')
          }
        } else {
          ElMessage.error('请检查是否填写完整')
        }
      })
    },
    onSubmit() {
      let form = this.$refs['formRef']

      form.validate((valid) => {
        if (valid) {
          this.disableButton = true
          request({
            method: 'post',
            url: '/api/uaa/forget',
            data: {
              id: this.user.id,
              email: this.user.email,
              password: CryptoJS.SHA256(this.user.password).toString(CryptoJS.enc.Hex),
              code: this.user.code
            }
          })
              .then(resp => {
                if (resp.data.code === 0) {
                  ElMessage.success('密码重置成功！')
                  router.replace({
                    path: '/login',
                    query: {
                      email: router.currentRoute.value.query.email,
                    }
                  });
                } else if (resp.data.code === 1302) {
                  ElNotification({
                    title: "链接已过期",
                    message: "请检查重置链接是否正确, 可以重新从邮件打开链接或者重新发送重置邮件",
                    type: "error",
                    duration: 0
                  })
                } else {
                  ElMessage.error(resp.data.msg)
                }
                this.disableButton = false
              })
              .catch(err => {
                this.disableButton = false
              })
        } else {
          ElMessage.error('请检查是否填写完整')
        }
      })
    }
  },
  created() {
    let params = router.currentRoute.value.query
    if ('email' in params && 'code' in params && 'id' in params) {
      this.isReset = true
      this.user.email = CryptoJS.enc.Utf8.stringify(CryptoJS.enc.Base64.parse(params.email))
      this.user.code = params.code
      this.user.id = params.id
    }
  }
}
</script>

<template>
  <el-icon @click="() => this.$router.back()" size="30" style="cursor: pointer">
    <Back/>
  </el-icon>

  <div class="outer">
    <h1 class="w-300 text-center">
      <router-link class="a-style" to="/" style="color: #4d4d4d">
        <span v-if="isReset">重置密码</span>
        <span v-else>忘记密码</span>
      </router-link>
    </h1>

    <!--    FROM-->
    <el-form
        ref="formRef"
        status-icon
        :model="user"
        :rules="rules"
    >
      <el-form-item prop="email" key="email">
        <el-input class="w-300 mb-5" size="large" v-model="user.email" placeholder="邮箱" clearable
                  maxlength="64" :disabled="isReset"/>
      </el-form-item>

      <div v-if="isReset">
        <el-form-item prop="password" key="password">
          <el-input class="w-300 mb-5" size="large" v-model="user.password" placeholder="密码" type="password"
                    show-password
                    clearable maxlength="64"/>
        </el-form-item>
        <el-form-item prop="passwordConfirm" key="passwordConfirm">
          <el-input class="w-300 mb-5" size="large" v-model="user.passwordConfirm" placeholder="再输入密码"
                    type="password"
                    show-password
                    clearable maxlength="64"/>
        </el-form-item>
        <el-form-item key="submit">
          <el-button class="w-300" type="primary" @click="onSubmit" :disabled="disableButton"
                     color="#ff9800" dark
          >
            重置密码
          </el-button>
        </el-form-item>
      </div>

      <el-form-item key="sendForgetUrl" v-else>
        <el-button class="w-300" type="primary" @click="sendForgetUrl" :disabled="isCountDown || disableButton"
                   color="#ff9800" dark
        >
          发送重置邮件&nbsp;&nbsp;
          <el-countdown
              v-show="isCountDown"
              format="ss"
              :value="countDownValue"
              @finish="() => this.isCountDown = false"
              :value-style="{ fontSize: '16px', color: 'gray' }"
          />
        </el-button>
      </el-form-item>

    </el-form>
    <!--    FORM END-->

    <p class=" w-300 text-center font-style">重置有问题？发邮件致shiziapi@126.com寻求帮助
    </p>
    <p class=" w-300 text-center font-style">已想起密码？
      <router-link class="a-style" to="/login">前往登录</router-link>
    </p>
  </div>
</template>

<style scoped>

.outer {
  position: absolute;
  top: 40%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.font-style {
  font-size: 14px;
  color: #737679;
}

.a-style {
  text-decoration: none;
  color: cornflowerblue;
}

</style>